import org.apache.log4j.Logger;

import java.lang.management.*;
import java.util.Arrays;
import java.util.List;

public class Metric {
    private static final long MB = 1048576L;
    private static Logger logger = Logger.getLogger(Metric.class);

    public static String printMemoryInfo() {
        MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
        MemoryUsage headMemory = memory.getHeapMemoryUsage();

        String info = String.format("init: %s\t max: %s\t used: %s\t committed: %s\t use rate: %s\n",
                headMemory.getInit() / MB + "MB",
                headMemory.getMax() / MB + "MB", headMemory.getUsed() / MB + "MB",
                headMemory.getCommitted() / MB + "MB",
                headMemory.getUsed() * 100 / headMemory.getCommitted() + "%"

        );



        MemoryUsage non_heap_Memory = memory.getNonHeapMemoryUsage();

        String non_info = String.format("init: %s\t max: %s\t used: %s\t committed: %s\t use rate: %s\n",
                non_heap_Memory.getInit() / MB + "MB",
                non_heap_Memory.getMax() / MB + "MB", non_heap_Memory.getUsed() / MB + "MB",
                non_heap_Memory.getCommitted() / MB + "MB",
                non_heap_Memory.getUsed() * 100 / non_heap_Memory.getCommitted() + "%"

        );
        String message = "\n堆内存:\n" + info + "非堆内存:\n" + non_info;
        return message;
    }

    public static String printGCInfo() {
        List<GarbageCollectorMXBean> garbages = ManagementFactory.getGarbageCollectorMXBeans();
        StringBuilder sbd = new StringBuilder("GC信息:\n");
        for (GarbageCollectorMXBean garbage : garbages) {
            String info = String.format("name: %s\t count:%s\t took:%s\t pool name:%s",
                    garbage.getName(),
                    garbage.getCollectionCount(),
                    garbage.getCollectionTime(),
                    Arrays.deepToString(garbage.getMemoryPoolNames()));
            sbd.append(info).append("\n");
        }
        return sbd.toString();
    }



    public static void printInfo(){
        String memoryInfo = printMemoryInfo();
        String gcInfo = printGCInfo();
        logger.debug(memoryInfo+gcInfo);

    }
}